<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Itemorder extends Backend
{

    /**
     * Goodsorder模型对象
     * @var \app\admin\model\order\Goodsorder
     */
    protected $model = null;
    protected $order_item_model=null;
    protected $user_model=null;
    protected $staff_model=null;
    protected $order_goods_model=null;
    protected $order_item_pay_model=null;
    protected $pay_model = null;
    protected $pay_way_list = [];
    protected $payways = [];
    const state_txt=[1=>'待支付',2=>'待发货',3=>'待收货',4=>'待评论',5=>'售后订单',6=>'已完成',7=>'已取消'
        ,8=>'退款列表',9=>'退款状态',10=>'退款失败',11=>'退款成功',12=>'退款中',13=>'取消退款'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Goodsorder;
        $this->order_item_model = new \app\admin\model\order\Item;
        $this->pay_model = new \app\admin\model\pay\Pay;
        $this->user_model = new \app\admin\model\User;
        $this->staff_model = new \app\admin\model\Staff;
        $this->pay_way_list = collection($this->pay_model->where('status','normal')->select())->toArray();
        $this->payways = [];
        foreach ($this->pay_way_list as $key => $value) {
            $this->payways[$value['id']] = $value['name'];
        }
        $this->order_goods_model = new \app\admin\model\order\Goods;
        $this->order_item_pay_model = new \app\admin\model\order\ItemPay;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("ontypeList", $this->model->getOntypeList());
        $this->view->assign("issupplementList", $this->model->getIssupplementList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $_where = [];
            if ($this->request->get("user_id")) {
                $_where = ['order.user_id'=>$this->request->get("user_id")];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //当前管理员店铺id
            $_admin = Session::get('adminshop');

            //当前店铺id
            $shop_id = Session::get('shop');
            $defaultWhere=[];
            $defaultWhere['data_type']='cards';

            if ($_admin == 1 && $_admin != $shop_id) {
                $defaultWhere['shop.id']= $shop_id;
            }else if ($_admin != 1) {
                $defaultWhere['shop.id']= $_admin;
            }

            //print_r($where);
            $list = $this->model
                ->with('shop,user')
                ->where($where)
                ->where($_where)
                ->where($defaultWhere)
                //->where('gdtype', '=', 0)
                ->order($sort, $order)
                ->paginate($limit);
            //print_r($list);exit;
            $total = $list->total();

            $rows = $list->items();

            foreach ($rows as &$val) {
                $pay_ways = Db::name('wanlshop_pay_out_trade t')
                            ->join('pay p','t.pay_way_id=p.id','left')
                            ->where(['t.order_id' => $val['id']])
                            ->column('p.name');
                $val['pay_ways'] = implode('/', $pay_ways);
                if (!empty($val['remarks'])) {
                    $val['order_no'] .= ',备注:'.strip_tags($val['remarks']);
                }
                $staff_names = '';
                if ($val['staff_ids'] && !empty($val['staff_ids'])) {
                    $staff_ids = explode(',', $val['staff_ids']);
                    $staffs = $this->staff_model->where(['id'=>['in',$staff_ids]])->column('name');

                    if (count($staffs) > 0) {
                        $staff_names = implode('/', $staffs);
                    }
                }
                $val['staffs'] = $staff_names;
                $goods = $this->order_item_model->where(['order_id'=>$val['id']])->select();
                $tmp=[];
                if($goods){
                    foreach ($goods as $k=>$v) {
                        $goods_name = "名称：".$v['name'] ." 价格：".$v['actual_price'];

                        //耗/充
                        $where = [];
                        $where['order_id'] = $val['id'];
                        $where['card_type'] = '4';
                        $exit_deduction_card =  $this->order_item_pay_model->where($where)->count();

                        if ($exit_deduction_card > 0) {
                            $goods_name .= "<span style='margin-left:5px;color: #f75444;border-radius: 10px;border: 1px solid red;font-size: 12px;padding: 3px;'>充</span>";
                        }

                        $where = [];
                        $where['order_id'] = $val['id'];
                        $where['is_gift'] = '1';
                        $goods_gift = $this->order_goods_model->where($where)->select();
                        if (count($goods_gift) > 0) {
                            foreach ($goods_gift as $key => $value) {
                                $goods_name .= "<br/>名称：".$value['title']." 价格：".$value['actual_payment']." <span style='margin-left:5px;color: #f75444;border-radius: 10px;border: 1px solid red;font-size: 12px;padding: 3px;'>赠</span>";
                            }
                        }

                        $tmp[$k] = $goods_name;


                    }
                }
                $val['goods_name'] = $tmp;

                //$orderinfo = $this->order_model->where(['id'=>$val['id']])->find();
                $userinfo = $this->user_model->where(['id'=>$val['user_id']])->find();
                $val['nickname'] = !empty($userinfo)?$userinfo['nickname']:'';


            }
            //echo 33333;exit;
            $result = array("total" => $total, "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        foreach ($params as $key => $value) {
            // 识别时间字段（根据你的字段名规则调整）
            if (strpos($key, 'time') !== false || strpos($key, 'date') !== false) {
                $value = str_replace('+', ' ', $value);
                $params[$key] = strtotime($value);
            }
        }

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 查看
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        $row['state_txt'] = self::state_txt[$row['state']]??"";
        $row['address'] = Db::name('wanlshop_order_address')
            ->where(['order_id' => $row['id']])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();

        $row['pay'] = Db::name('wanlshop_pay')
            ->where(['order_id' => $row['id'], 'type' => 'goods'])
            ->find();
        $row['shop'] = Db::name('wanlshop_shop')
            ->where(['id' => $row['shop_id']])
            ->find();

        $row['user'] = Db::name('user')
            ->where(['id' => $row['user_id']])
            ->field('id,nickname,username,mobile')
            ->find();
        $couponPrice=0;
        if($row['coupon_id']){
            $coupon = Db::name('wanlshop_coupon_receive')
                ->where(['order_id' => $row['id']])
                ->find();
            $couponPrice= sprintf('%.2f',$coupon['price']);
        }
        $this->view->assign("couponPrice", $couponPrice);

        if($row['isrecharge'] == 1){//充值卡续卡订单
            $order_item_ids = Db::name('wanlshop_order_item_recharge')->where(['order_id' => $row['id']])->column('order_item_id');
            $info = Db::name('wanlshop_order_item')->where(['id' => ['in',$order_item_ids]])->select();
        }else{
            $info = Db::name('wanlshop_order_item')
                    ->where(['order_id' =>  $row['id']])
                    ->select();
        }

        if($info){
            if ($row['isrecharge'] == 1) {
                //充值卡续卡订单数据处理
                foreach ($info as &$value){
                    $where = [];
                    $where['order_id'] = $row['id'];
                    $where['order_item_id'] = $value['id'];
                    $recharge_info = Db::name('wanlshop_order_item_recharge')->where($where)->find();

                    $value['detail']='';
                    $value['refund_price']=0;
                    $value['refund_price'] =sprintf('%.2f',$recharge_info['actual_price'] + $recharge_info['gift']);
                    $value['detail']="剩余可退本金：{$recharge_info['actual_price']}\r\n剩余可退赠金：{$recharge_info['gift']}";
                    $value['name'] .= '[续卡]';
                    $value['save_price'] = $recharge_info['actual_price'];
                    $value['price'] = $recharge_info['actual_price'];
                    $value['actual_price'] = $recharge_info['actual_price'];

                    $itemPay = Db::name('wanlshop_order_item_pay')
                        ->where(['order_id' =>  $row['id']])
                        ->select();
                    $value['deduction_price'] =0;
                    $value['deduction_times'] =0;
                    if($itemPay){
                        foreach ($itemPay as $val){
                            if($val['card_type']==4){
                                $value['deduction_price'] +=$val['money'];
                                $value['deduction_price'] = sprintf('%.2f',$value['deduction_price']);
                            }else{
                                if($value['id']==$val['order_goods_id']){
                                    $value['deduction_times'] +=$val['total'];
                                }

                            }
                        }
                    }

                    $staff_names = '';
                    if ($recharge_info['staff_ids'] && !empty($recharge_info['staff_ids'])) {
                        $staff_ids = explode(',', $recharge_info['staff_ids']);
                        $staffs = $this->staff_model->where(['id'=>['in',$staff_ids]])->column('name');

                        if (count($staffs) > 0) {
                            $staff_names = implode('/', $staffs);
                        }
                    }
                    $value['staffs'] = $staff_names;
                }
            }else{
                foreach ($info as &$value){
                    $value['detail']='';
                    $value['refund_price']=0;
                    if($value['type']==4){
                        $value['refund_price'] =sprintf('%.2f',$value['spent'] + $value['gift']);
                        $value['detail']="剩余可退本金：{$value['spent']}\r\n剩余可退赠金：{$value['gift']}";
                    }else{
                        if($value['total']==$value['spent']){
                            $value['refund_price'] +=sprintf('%.2f',$value['actual_price']);
                            $value['detail']="剩余可退金额：{$value['actual_price']}\r\n";
                        }else{
                            $itemInfo = Db::name('wanlshop_order_item_info i')->join('wanlshop_goods g','i.goods_id=g.id','left')
                                ->where(['order_item_id' =>  $value['id']])->field('g.title,(i.spent * i.price) as refund_price')
                                ->select();
                            foreach ($itemInfo as $valInfo){
                                $value['refund_price'] +=sprintf('%.2f',$valInfo['refund_price']);
                                $value['detail']=$valInfo['title']."剩余可退金额：{$valInfo['refund_price']}\r\n";
                            }
                        }

                    }
                    $itemPay = Db::name('wanlshop_order_item_pay')
                        ->where(['order_id' =>  $value['order_id']])
                        ->select();
                    $value['deduction_price'] =0;
                    $value['deduction_times'] =0;
                    if($itemPay){
                        foreach ($itemPay as $val){
                            if($val['card_type']==4){
                                $value['deduction_price'] +=$val['money'];
                                $value['deduction_price'] = sprintf('%.2f',$value['deduction_price']);
                            }else{
                                if($value['id']==$val['order_goods_id']){
                                    $value['deduction_times'] +=$val['total'];
                                }

                            }
                        }
                    }

                    $staff_names = '';
                    if ($value['staff_ids'] && !empty($value['staff_ids'])) {
                        $staff_ids = explode(',', $value['staff_ids']);
                        $staffs = $this->staff_model->where(['id'=>['in',$staff_ids]])->column('name');

                        if (count($staffs) > 0) {
                            $staff_names = implode('/', $staffs);
                        }
                    }
                    $value['staffs'] = $staff_names;
                }
            }
        }
        $row['info']=$info;
        $row['order_pay_out_trade']=Db::name('wanlshop_pay_out_trade t')->join('pay p','t.pay_way_id=p.id','left')
            ->where(['t.order_id' => $row['id']])->field(['p.name'])
            ->find();
        $goodsCount = count($row['info']);
        $this->view->assign("goodsCount", $goodsCount);
        $payTime = isset($row['paymenttime']) ? date('Y-m-d H:i:s',$row['paymenttime']):"";
        $this->view->assign("payTime", $payTime);
        //赠送商品
        $where = [];
        $where['order_id'] = $row['id'];
        $where['is_gift'] = '1';
        $goods_gift = $this->order_goods_model->field('title as name,"" as image,"" as staffs,0 as save_price,0 as price,0 as actual_price')->where($where)->select();
        foreach ($goods_gift as $key => $g_value) {
            $g_value['name'] .= " <span style='margin-left:5px;color: #f75444;border-radius: 10px;border: 1px solid red;font-size: 12px;padding: 3px;'>赠</span>";
        }

        //使用卡项
        $card_list = $this->order_item_pay_model->where(['order_id'=>$row['id']])->select();
        if (count($card_list)>0) {
            $type_list = ['无','有限次卡','不限次卡','通卡','充值卡','折扣卡'];
            foreach ($card_list as $card_key => &$card_value) {
                $card_value['card_type_text'] = $type_list[$card_value['card_type']];
                if ($card_value['card_type'] == 4) {//充值卡
                    $card_info = $this->order_item_model->where(['id'=>$card_value['order_item_info_id']])->find();
                    $card_value['card_name'] = empty($card_info)?'':$card_info['name'];
                }else{
                    $order_item_info = $this->order_item_info_model->where(['id'=>$card_value['order_item_info_id']])->find();
                    if (!empty($order_item_info)) {
                        $card_info = $this->order_item_model->where(['id'=>$order_item_info['order_item_id']])->find();
                        $card_value['card_name'] = empty($card_info)?'':$card_info['name'];
                    }else{
                        $card_value['card_name'] = '';
                    }
                }
            }
        }
        $this->view->assign("cardList", $card_list);
        $this->view->assign("cardTimes", count($card_list));


        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign('gift', $goods_gift);

            return $this->view->fetch();
        }

    }

}
